/**
 * MIT License
 *
 * Copyright (c) 2024 小村程序员
 * Email: 397237738@qq.com
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package org.open.cobertura.core.instrument;

import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Opcodes;
import org.open.cobertura.report.html.CreateHtmlReport;
import org.open.cobertura.util.Crc64;
import org.open.cobertura.util.DebuggerUtil;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.logging.Logger;

/**
 * Opentester-cobertura插桩类入口
 */
public class CoberturaInstrument {
    private final static Logger logger = Logger.getLogger(CoberturaInstrument.class.getName());
    /**
     * 给类进行插桩
     * @param classFile
     * @return 字节码是用于后面适配agent的
     */
    public byte[] instrument(final String classFile,final String outClassFile){
        byte[] modifiedClassBytes=null;
        ClassReader cr = null;
        FileInputStream fis=null;
        ClassWriter cw=null;
        try {
            byte[] source = new byte[(int) new File(classFile).length()];
            fis= new FileInputStream(classFile);
            fis.read(source);
            final long classId= Crc64.crc64Long(source);
            cr = new ClassReader(source);
            cw= new ClassWriter(cr, ClassWriter.COMPUTE_MAXS|ClassWriter.COMPUTE_FRAMES);
            CoberturaClassProbeVisitor couberturaClassProbeVisitor=new CoberturaClassInstrumenter(Opcodes.ASM9,cw);
            CoberturaClassProbeAdapter classFieldProbeArrayStub=new CoberturaClassProbeAdapter(Opcodes.ASM9,couberturaClassProbeVisitor,classId);
            cr.accept(classFieldProbeArrayStub,0);
            modifiedClassBytes = cw.toByteArray();
            try (FileOutputStream fos = new FileOutputStream(outClassFile)) {
                fos.write(modifiedClassBytes);
            }
        } catch (IOException e) {
            logger.info("插桩失败"+e.getMessage());
        }finally {
            if(fis!=null){
                try {
                    fis.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
        return modifiedClassBytes;
    }

    public byte[] instrument(final byte[] rawClasses,String className){
        byte[] modifiedClassBytes=null;
        ClassReader cr = null;
        ClassWriter cw=null;
        try {
            final long classId= Crc64.crc64Long(rawClasses);
            cr = new ClassReader(rawClasses);
            cw= new ClassWriter(cr, ClassWriter.COMPUTE_MAXS|ClassWriter.COMPUTE_FRAMES);
            CoberturaClassProbeVisitor couberturaClassProbeVisitor=new CoberturaClassInstrumenter(Opcodes.ASM9,cw);
            CoberturaClassProbeAdapter classFieldProbeArrayStub=new CoberturaClassProbeAdapter(Opcodes.ASM9,couberturaClassProbeVisitor,classId);
            cr.accept(classFieldProbeArrayStub,0);
            modifiedClassBytes = cw.toByteArray();
            DebuggerUtil.writeClass(modifiedClassBytes,className);
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("插桩失败"+e.getMessage());
        }finally {
        }
        return modifiedClassBytes;
    }
}
